/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import gestor.Reputacao;
import jade.core.AID;
import jade.core.Agent;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import java.util.Map.Entry;
import java.util.TreeMap;


public class Mercado {

	static public String propertiesToMessage(TreeMap<String, String> properties) {
		String res = "";

		for(Entry<String, String> p: properties.entrySet()) {
			if(res.length() != 0)
				res += ";";

			res += p.getKey() + ":" + p.getValue();
		}

		return res;
	}

	static public TreeMap<String, String> messageToProperties(String message) {
		TreeMap<String, String> properties = new TreeMap<String, String>();
		String[] sp = message.split(";");
		String[] x;

		for(String s: sp) {
			x = s.split(":");
			if(x.length == 2)
				properties.put(x[0], x[1]);
		}

		return properties;
	}

	static public void ratePositive(Agent a, String nome) {
		try {
			DFAgentDescription[] desc = DF.search(a, "gestor");

			if(desc.length == 1) {
				DFAgentDescription d = desc[0];
				AID aid = d.getName();

				ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
				msg.addReceiver(aid);
				msg.setOntology("positivo");
				msg.setContent(nome);
				a.send(msg);
			}
		} catch (FIPAException ex) {

		}
	}

	static public void rateNegative(Agent a, String nome) {
		try {
			DFAgentDescription[] desc = DF.search(a, "gestor");

			if(desc.length == 1) {
				DFAgentDescription d = desc[0];
				AID aid = d.getName();

				ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
				msg.addReceiver(aid);
				msg.setOntology("negativo");
				msg.setContent(nome);
				a.send(msg);
			}
		} catch (FIPAException ex) {

		}
	}
	
	static public Reputacao getRate(Agent a, String nome) {
		try {
			DFAgentDescription[] desc = DF.search(a, "gestor");

			if(desc.length == 1) {
				DFAgentDescription d = desc[0];
				AID aid = d.getName();

				ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
				msg.addReceiver(aid);
				msg.setOntology("reputacao");
				msg.setContent(nome);
				a.send(msg);
				
				MessageTemplate template = MessageTemplate.and(
					MessageTemplate.MatchPerformative(ACLMessage.INFORM),
					MessageTemplate.MatchOntology("reputacao") );
				
				ACLMessage resp = a.blockingReceive(template);
				return new Reputacao(resp.getContent());
			}
			else
				return null;
		} catch (FIPAException ex) {
			return null;
		}
	}
}
